# coding=utf-8

"""
日志默认输出到程序运行当前目录下的 log 目录，系统自动创建目录结构
日志分为四个级别进行记录，分别是 info, error, warn, debug

"""

import sys, os, datetime
import logging
import time
from logging.handlers import RotatingFileHandler

logLevelInfo = logging.INFO
logLevelError = logging.ERROR
logLevelDebug = logging.DEBUG
logLevelWarn = logging.WARN

logPath = ''

logInfo = logging.Logger(logging.INFO)
logDebug = logging.Logger(logging.DEBUG)
logError = logging.Logger(logging.ERROR)
logWarn = logging.Logger(logging.WARN)

# log format
FORMAT = '%(asctime)-15s %(levelname)s -- %(message)s'
defaultFormat = logging.Formatter(FORMAT)

# log stream
logStream = logging.StreamHandler(stream=sys.stdout)
logStream.setFormatter(defaultFormat)
encode = 'utf8'


def setLogPath(path):
    """
    设置日志路径
    """
    logPath = path
    # log path
    if (not os.path.exists(logPath)):
        os.makedirs(logPath)
    logDate = datetime.datetime.now().strftime('%Y%m%d')
    # log info
    fileHandlerInfo = logging.handlers.RotatingFileHandler('%s/log_%s_info.log' % (logPath, logDate), mode='a',maxBytes=1024 * 1024 * 500, backupCount=100, encoding=encode,delay=0)
    fileHandlerInfo.setFormatter(defaultFormat)
    logInfo.addHandler(fileHandlerInfo)

    # log debug
    fileHandlerDebug = logging.handlers.RotatingFileHandler('%s/log_%s_debug.log' % (logPath, logDate), mode='a',
                                                            maxBytes=1024 * 1024 * 50, backupCount=100, encoding=encode,
                                                            delay=0)
    fileHandlerDebug.setFormatter(defaultFormat)
    logDebug.addHandler(fileHandlerDebug)

    # log error
    fileHandlerError = logging.handlers.RotatingFileHandler('%s/log_%s_error.log' % (logPath, logDate), mode='a',
                                                            maxBytes=1024 * 1024 * 50, backupCount=100, encoding=encode,
                                                            delay=0)
    fileHandlerError.setFormatter(defaultFormat)
    logError.addHandler(fileHandlerError)

    # log warn
    fileHandlerWarn = logging.handlers.RotatingFileHandler('%s/log_%s_warn.log' % (logPath, logDate), mode='a',
                                                           maxBytes=1024 * 1024 * 50, backupCount=100, encoding=encode,
                                                           delay=0)
    fileHandlerWarn.setFormatter(defaultFormat)
    logWarn.addHandler(fileHandlerWarn)


def setLogLevel(level):
    logInfo.setLevel(level)
    logDebug.setLevel(level)
    logError.setLevel(level)
    logWarn.setLevel(level)


def error(msg):
    logError.error(msg)


def warn(msg):
    logWarn.warn(msg)


def info(msg):
    logInfo.info(msg)


def debug(msg):
    logDebug.debug(msg)
